package com.cloudweb.oa.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.service.WorkflowUrgeService;
import com.redmoon.oa.visual.FormDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class WorkflowUrgeServiceImpl implements WorkflowUrgeService {

    @Autowired
    UserCache userCache;

    @Override
    public JSONArray getUrgeCount(@RequestParam(value="flowId") int flowId) {
        String sql = "select id from ft_supervise_handle where flow_id=" + flowId + " and cws_status=1";
        Map<String, JSONObject> map = new HashMap<>();
        FormDAO fdao = new FormDAO();
        for (FormDAO dao : fdao.list("supervise_handle", sql)) {
            String userSupervised = dao.getFieldValue("user_supervised");
            if (map.containsKey(userSupervised)) {
                JSONObject json = map.get(userSupervised);
                int c = json.getIntValue("count");
                c += 1;
                json.put("count", c);
                map.put(userSupervised, json);
            } else {
                JSONObject json = new JSONObject();
                json.put("count", 1);
                json.put("flowId", dao.getFlowId());
                map.put(userSupervised, json);
            }
        }

        JSONArray ary = new JSONArray();
        for (String userSupervised : map.keySet()) {
            JSONObject json = new JSONObject();
            User user = userCache.getUser(userSupervised);
            if (user != null) {
                json.put("user", user.getRealName());
                JSONObject jsonObject = map.get(userSupervised);
                json.put("count", jsonObject.getIntValue("count"));
                json.put("flowId", jsonObject.getIntValue("flowId"));
                ary.add(json);
            }
        }
        return ary;
    }
}
